<!--
  @Descripttion：导入组件
  @Author：zqy
  @Date：2020-11-04 15:25:39
  @Last Modified by：zqy
  @Last Modified time：2020-11-04 15:25:39
-->
<template>
  <el-dialog
    v-el-drag-dialog 
    :title="title"
    :visible.sync="dialogVisible"
    width="600px"
    :before-close="closeDialog"
    :close-on-click-modal="false"
    append-to-body
  >
    <div slot="title" class="custom-dialog-title">
      <span class="el-dialog__title">{{title}}</span>
      <el-button v-if="taskConfig && taskConfig.apiPrefix" type="text" style="color:#3DC094" @click="handleSeeTask">查看离线任务</el-button>
    </div>
    <el-form ref="refForm" :rules="formRules" :model="formData" size="mini" label-width="100px">
      <el-form-item label="模板名称:" prop="templateCode">
        <el-select v-model="formData.templateCode">
          <el-option v-for="(item,index) in config" :key="index" :label="item.name" :value="item.code"/>
        </el-select>
      </el-form-item>
      <el-form-item label="上传文件" prop="file">
        <import-excel
          ref="refUploader"
          :action="activeConfig.apiUrl"
          :act-headers="activeConfig.headers || null"
          :data="uploadParams"
          :disabled="!formData.templateCode"
          @upload-finish="uploadFinish=true"
          @upload-success="uploadSuccess"
          @on-change="fileChange"
          @change-finish="changeUploadStatus"
        />
      </el-form-item>
      <el-form-item 
        v-show="activeConfig.async" 
        label="任务名称:" 
        prop="taskName" 
        :rules="[{ required: !!activeConfig.async, message: '请输入任务名称', trigger: 'blur' }]"
      >
        <el-input
          v-model="formData.taskName"
          placeholder="请输入离线任务名称"
          maxlength="60"
          style="width:250px"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button size="mini" @click="closeDialog">取 消</el-button>
      <el-button type="primary" size="mini" v-if="!uploadFinish"  :loading="uploading" @click="handleSure">确 定</el-button>
    </div>
    <import-task 
      v-if="taskVisible"
      :visible.sync="taskVisible"
      :taskConfig="taskConfig"
    ></import-task>
  </el-dialog>
</template>

<script>
import ImportExcel from './ImportExcel'
// import ImportTask from './importTask'
import drag from '../../directives/el-drag-dialog/drag'
export default {
  name: 'ImportFiles',
  components: { ImportExcel },
  directives:{
    'el-drag-dialog':drag
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '导入数据'
    },
    config:{
      required: true,
      type:Array,
      default:()=>{
        return [
          {
            code:'',// 导入模板的编码(需产品提供)
            name:'',//导入模板的名称(需产品提供)
            async:false,//是否异步导入(需后端提供)
            apiUrl:'',//导入数据的接口地址(后端提供)
            headers:null, // 发送请求的header参数
            paramsRaw:{},// 关键非必填字段,可以存任意值（具体值和JSON字符串）
            bizParam:'' ,// bizParam参数值，可以是任意的字符串或者json
            validateFunc:null,//导入操作前的校验函数，该函数需返回true/false,或者返回一个 promise
          }
        ]
      }
    },
    taskConfig:{
      type:Object,
      default:()=>{
        return {
          apiPrefix:'',// 应用接口前缀 (后端提供)
          checkRowApi:'',//临时数据校验行接口 (后端提供)
          checkApi:'',// 校验业务数据 (后端提供)
          completeApi:'',//执行临时数据写入业务数据表，完成导入任务 (后端提供)
          exportTempApi:'', //导出待处理临时数据(后端提供)
          taskFiltersRaw:[],  // 任务查询条件
          saveTempEmpty:false,// 是否保存临时数据null值为空字符串：true  保存为空字符串，false保存为null
          saveTempApi:'',//自定义临时数据保存接口
        }
      }
    }, // 离线任务接口配置
    successFun: {
      type: [String,Function],
      default: undefined
    },
  },
  data() {
    return {
      formData: {
        templateCode:'',//模板编码
        taskName:'',//任务名称
      },  
      formRules: {
        templateCode: [
          { required: true, message: '请选择名称', trigger: 'change' }
        ],
        file: [
          { required: true, message: '请选择文件', trigger: 'change' }
        ]
      },
      taskVisible:false,
      writeDataAPi:'', // 离线导入写入数据表的接口地址
      checkDataApi:'' ,// 离线导入校验数据行的接口地址
      uploadFinish:false,//是否导入结束
      uploading:false,//是否导入中
    }
  },

  computed: {
    dialogVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    },
    // 当前需要导入的模板
    activeConfig(){
      const tmpArr=this.config.filter(v=>v.code===this.formData.templateCode)
      return (tmpArr && tmpArr[0]) || ''
    },
    // 当前模板对应的上传参数
    uploadParams(){
      let params={
        taskName:this.formData.taskName || ''
      }
      const menuCode=(this.$route.query && this.$route.query.menuCode) || ''
      if(menuCode){
        params.menuCode=menuCode
      }
      const tmpArr=this.config.filter(v=>v.code===this.formData.templateCode)
      if(tmpArr && tmpArr.length){
        params.templateCode = this.formData.templateCode
        const {paramsRaw,bizParam}=tmpArr[0]
        if(paramsRaw){
          params={...params,...paramsRaw}
        }
        if(bizParam){
          let bizParamStr=''
          try {
            bizParamStr= typeof bizParam !=='string'? JSON.stringify(bizParam) : bizParam
          } catch (error) {
            bizParamStr=''
          }
          params.bizParam = bizParamStr
        }
      }
      // console.log('上传参数',params)
      return params 
    }
  },
  watch:{
    'formData.templateCode'(val,oldVal){
      this.$refs.refUploader && this.$refs.refUploader.resetUpload()
    }
  },
  methods: {
    closeDialog() {
      this.dialogVisible = false
      this.$refs.refUploader && this.$refs.refUploader.clearUploadFile()
      this.$emit('close')
    },
    fileChange(file){
      this.$set(this.formData,'file',file)
      if(file && file.name){
        const taskName= file.name.replace('.xlsx','').replace('.xls','')
        this.$set(this.formData,'taskName',taskName)
      }
      this.$refs.refForm.validateField('file',()=>{})
      if(!file){
        this.uploading= false
      }
    },
    changeUploadStatus(val){
      this.uploading=false
      this.uploadFinish=val
    },
    uploadSuccess(res) {
      this.uploading=false
      this.uploadFinish=true
      if(this.successFun){
        if(this.successFun instanceof Function){
          this.successFun(this.activeConfig,res)
        }else{
          this.$message.success(this.successFun)
        }
        this.$emit('success',res)
        this.closeDialog()
        return
      }
      if(this.activeConfig.async){
        // 异步导入
        this.$message.success('导入进行中，请到离线任务查看结果')
      }else{
        // 同步导入
        if(res && res.msg){
          this.$message.success('部分导入成功')
        }else{
          this.$message.success('导入成功')
        }
        this.$emit('success',res)
        this.closeDialog()
      }
    },
    handleSure(){
      this.$refs['refForm'].validate((valid) => {
        if (valid) {
          // 检查是否存在校验函数，若存在则执行
          const validateFunc = this.activeConfig.validateFunc
          if(validateFunc instanceof Function){
            const result = validateFunc()
            if (result instanceof Promise) {
              return result.then(res => {
                // 执行导入
                this.uploading=true
                this.$refs.refUploader.submit()
              })
            } else {
              if(!result){
                return
              }
            }
          }

          this.uploading=true
          this.$refs.refUploader.submit()
        }
      })
    },
    // 查看离线任务
    handleSeeTask(){
      /* window.parent.postMessage({
        flag: 'portalPage',
        extraData: {
          name:'ImportTask',
          query:{}
        }
      }, '*') */
      if(!this.taskConfig || !this.taskConfig.apiPrefix){
        this.$message.warning('未配置离线任务完整参数，无法查看')
        return
      }
      this.taskVisible = true

    }
  }
}
</script>
<style lang='scss' scoped>
/* @import url(); 引入css类 */

</style>
